import 'dart:async';

import 'package:get/get.dart';

class GlobalService extends GetxController {
  DateTime sendSmsAt = DateTime.fromMillisecondsSinceEpoch(0);
  DateTime sendEmailAt = DateTime.fromMillisecondsSinceEpoch(0);
  String lastPhone = "";
  String lastEmail = "";
  final RxInt remainSeconds = 0.obs;
  final RxInt remainEmailSeconds = 0.obs;
  Timer? _timer_sms;
  Timer? _timer_email;
  final int _totalSmsSeconds = 60;
  final int _totalEmailSeconds = 60;
  void startSmsCountDown(String phone) {
    lastPhone = phone;
    sendSmsAt = DateTime.now();
    _startSmsTimer();
  }

  void startEmailCountDown(String email) {
    lastEmail = email;
    sendEmailAt = DateTime.now();
    _startEmailTimer();
  }

  void _startSmsTimer() {
    _timer_sms?.cancel();

    int passed = DateTime.now().difference(sendSmsAt).inSeconds;
    int left = _totalSmsSeconds - passed;
    if (left <= 0) {
      remainSeconds.value = 0;
      return;
    }

    remainSeconds.value = left;

    _timer_sms = Timer.periodic(const Duration(seconds: 1), (timer) {
      remainSeconds.value--;
      if (remainSeconds.value <= 0) {
        timer.cancel();
      }
    });
  }

  void _startEmailTimer() {
    _timer_email?.cancel();

    int passed = DateTime.now().difference(sendEmailAt).inSeconds;
    int left = _totalEmailSeconds - passed;
    if (left <= 0) {
      remainEmailSeconds.value = 0;
      return;
    }

    remainEmailSeconds.value = left;

    _timer_email = Timer.periodic(const Duration(seconds: 1), (timer) {
      remainEmailSeconds.value--;
      if (remainEmailSeconds.value <= 0) {
        timer.cancel();
      }
    });
  }

  @override
  void onClose() {
    _timer_sms?.cancel();
    _timer_email?.cancel();
    super.onClose();
  }

  void cancelPhone() {
    _timer_sms?.cancel();
    remainSeconds.value = 0;
  }

  void cancelEmail() {
    _timer_email?.cancel();
    remainEmailSeconds.value = 0;
  }
}
